/* Copyright © 2010 LPRM
Universidade Federal do Espírito Santo - RNP-GT CWTools

This file is part of GW-Android.

GW-Android is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

GW-Android is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with GW-Android. If not, see <http://www.gnu.org/licenses/>. */
package br.ufes.cwtools.android.components;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.util.List;

import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import br.ufes.cwtools.android.Constants;
import br.ufes.cwtools.android.R;
import br.ufes.cwtools.android.components.map.GeoObject;
import br.ufes.cwtools.android.components.map.GeoObjectItemizedOverlay;
import br.ufes.cwtools.android.components.map.GeoObjectsParser;

import com.google.android.maps.MapActivity;
import com.google.android.maps.MapView;

public class Map extends MapActivity {
	/* Como esta classe não herda Component é preciso tomar cuidado especial
	 * para lidar com o ciclo de vida dos componentes (incluindo incluir no
	 * result o intent recebido, para ser passado adiante). */
	private static final String TAG = "Map (Component)";
	private static final String GOOGLE_MAPS_KEY = Constants.MAPS_API_KEY;
	private static final int MENU_VIEW_MAP = 1;
	private static final int MENU_VIEW_SAT = 2;

	private List<GeoObject> geoObjects;
	private MapView mapView;

	@Override
	protected void onCreate(Bundle icicle) {
		super.onCreate(icicle);
		mapView = new MapView(this, GOOGLE_MAPS_KEY);
		mapView.setClickable(true);
		mapView.setBuiltInZoomControls(true);
		this.setContentView(mapView);
		
		this.populateGeoObjects();
	}

	@Override
	public void finish() {
		this.setResult(RESULT_OK, this.getIntent());
		super.finish();
	}

	// TODO Colocar o método num lugar apropriado para ser reusado.
	// Referência: http://www.devx.com/wireless/Article/39810/1954
	private InputStream openHttpConnection(String sUrl) throws IOException {
		InputStream in = null;
		int response = -1;

		URL url = new URL(sUrl);
		URLConnection conn = url.openConnection();
		if (!(conn instanceof HttpURLConnection)) {
			throw new IOException("Not an HTTP connection.");
		}
		
		try {
			HttpURLConnection httpConn = (HttpURLConnection) conn;
			httpConn.setAllowUserInteraction(false);
			httpConn.setInstanceFollowRedirects(true);
			httpConn.setRequestMethod("GET");
			httpConn.connect();
			
			response = httpConn.getResponseCode();
			if (response == HttpURLConnection.HTTP_OK) {
				in = httpConn.getInputStream();
			}
		} catch (Exception e) {
			throw new IOException("Error connecting.");
		}
		return in;
	}
	
	// Deixa aí; acho que vou reaproveitar isso no ServerCom.
	/*private String downloadText(String sUrl) {
		InputStream in = null;
		try {
			in = openHttpConnection(sUrl);
		} catch (IOException e) {
			Log.w(TAG, "Falha ao estabelecer conexão para obter a URL: " + sUrl);
			return "";
		}
		
		BufferedReader reader = new BufferedReader(new InputStreamReader(in));
		StringBuilder stringBuilder = new StringBuilder();
		String s;
		try {
			while ((s = reader.readLine()) != null) {
				stringBuilder.append(s);
			}
		} catch (IOException e) {
			Log.w(TAG, "Erro ao ler a partir da URL: " + sUrl);
			return "";
		}
		return stringBuilder.toString();
	}*/
	
	private void populateGeoObjects() {
		// Carrega o XML dos objetos a partir de uma URL.
//		InputStream source = null;
//		try {
//			String sUrl = "http://192.168.1.3:8000/sample_geo_objects.xml";
//			String sUrl = "http://joinus.inf.ufes.br:8080/JoinUs-ApplicationServer/UserMap?campaignId=280";
//			source = openHttpConnection(sUrl);
//		} catch (IOException e) {
//			Log.w(TAG, "Falha ao estabelecer para obter XML dos objetos.");
//			return;
//		}
		InputStream source = this.getResources().openRawResource(R.raw.sample_geo_objects);
		
		geoObjects = GeoObjectsParser.parse(source);  // Obtém lista de GeoObjects a serem mostrados no mapa.
		if (geoObjects == null) {
			Log.d(TAG, "Parser returned null GeoObject list.");
			return;
		}

		Drawable drawable1 = this.getResources().getDrawable(R.drawable.camera_icon);
		Drawable drawable2 = this.getResources().getDrawable(R.drawable.androidmarker);
		GeoObjectItemizedOverlay itemizedOverlay1 = new GeoObjectItemizedOverlay(drawable1, this);
		GeoObjectItemizedOverlay itemizedOverlay2 = new GeoObjectItemizedOverlay(drawable2, this);
		for (GeoObject g : geoObjects) {
			if (g.getType().equalsIgnoreCase(GeoObject.TYPE_PHOTO)) {
				mapView.getOverlays().add(itemizedOverlay1);
				itemizedOverlay1.addGeoObject(g);
			} else if (g.getType().equalsIgnoreCase(GeoObject.TYPE_USER)) {
				mapView.getOverlays().add(itemizedOverlay2);
				itemizedOverlay2.addGeoObject(g);
			} else {
				// Invalid type?
			}
		}
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		menu.add(0, MENU_VIEW_MAP, 0, "Mapa");
		menu.add(0, MENU_VIEW_SAT, 0, "Satélite");
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case MENU_VIEW_MAP:
			mapView.setSatellite(false);
			return true;
		case MENU_VIEW_SAT:
			mapView.setSatellite(true);
			return true;
		default:
			return false;
		}
	}

	@Override
	protected boolean isRouteDisplayed() {
		return false;
	}
}